<?php


/*

   function sess_open($sess_path, $sess_name) {
      print "Session opened.<br />";
      print "Sess_path: $sess_path<br />";
      print "Sess_name: $sess_name<br /><br />";
      return true;
   }

   function sess_close() {
      print "Session closed.<br /><br />";
      return true;
   }

   function sess_read($sess_id) {
      print "Session read.<br />";
      print "Sess_ID: $sess_id<br /><br />";
      return '';
   }

   function sess_write($sess_id, $data) {
      print "Session value written.<br />";
      print "Sess_ID: $sess_id<br />";
      print "Data: $data<br /><br />";
      return true;
   }

   function sess_destroy($sess_id) {
		print "Session destroy called.<br />";
		print "Sess_ID: $sess_id<br /><br />";
      return true;
   }

   function sess_gc($sess_maxlifetime) {
      print "Session garbage collection called.<br />";
      print "Sess_maxlifetime: $sess_maxlifetime<br /><br />";
      return true;
   }
	print "session save handler being set now<br /><br />";
   session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
	print "session staring now<br /><br />";
    session_start();

	print "session foo being set now<br /><br />";
    $_SESSION['foo'] = "bar";
   print "Some text<br /><br />";
	print "session baz being set now<br /><br />";
    $_SESSION['baz'] = "wombat";


	print "session foo being echoed now<br /><br />";
	echo $_SESSION['foo'],  "<br /><br />";

	print "session foo being unset now<br /><br />";
	unset($_SESSION['foo']);

	print "session foo being set now<br /><br />";
    $_SESSION['foo'] = "cat";

	print "session foo being echoed now<br /><br />";
	echo $_SESSION['foo'],  "<br /><br />";

//sessions are compiled, then written
//first when session start is called, a dread is done...if no session destroy is called then a write is done before closing
//session_destroy();	//if session destroy is called, it doesnt even bother writing!


*/

/*
sesson handlin

  First, edit php.ini.  There is a line in that file that by default reads:

          session.save_handler = files

     Change that line to read:

          session.save_handler = user




CREATE TABLE sessions (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  session_id VARCHAR(32) default NOT NULL,
  data TEXT,
  created_at datetime NOT NULL default '0000-00-00 00:00:00',
  updated_at datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (id),
  KEY index_sessions_on_session_id (session_id),
  KEY index_sessions_on_updated_at (updated_at)
);



CGI::Session::ActiveRecordStore::Session.set_table_name "my_sessions"

*/


//	i have decided not to extend m_arb coz functions are simple and dont require complexity such as validation before/afrer save checks
//require(CONFIG . 'Database_connections.php'); //this seems to be required already in initializer marb dbconn

ini_set("session.hash_function", 0);
ini_set("session.save_handler", 'user');
new Database_session_store();

class Database_session_store {

	private static $sess_max_life = 0;

	function Database_session_store() {
		self::$sess_max_life = get_cfg_var("session.gc_maxlifetime");
		session_set_save_handler( 
			array(&$this, 'open'),
			array(&$this, 'close'),
			array(&$this, 'read'),
			array(&$this, 'write'),
			array(&$this, 'destroy'),
			array(&$this, 'gc')
		);
	}

	function open($save_path, $session_name) {
		if (!isset($GLOBALS['dbh'])) {$GLOBALS['dbh'] = Database_connections::get_connection();}
		self::$sess_max_life = ini_get("session.gc_maxlifetime");

		return true;
	}

	function close() {
		//keeping a persistents db conn.
		return true;
	}

	//i figured that in any case unless a session destroy is called a read and write is done, initually session start does a read to memory
	//then it compiles all the session variables and writes it at the end of teh script to db, id session destroy is called, it just doesnt //do a write, it does its internal destroy, but the session variables in memory can still be referenced

	//INITAILLY in a read its doin a check to see if record exists updates it and returns it, in write it does a check again to see if it exixts and //if it does updates it else inserts a new rec.
	//since everytime its doin a read and write, i might as well create a new record on read if it doesnt exists, and just update in write
	//saves me a trip to the db
	function read($sess_id)
	{
		/*updated_at = 1;$sess_max_life = 5;expiry = 6;	time() = 5.5;updated_at >= time() - $sess_max_life 	*/
// 		echo "read";
		$curr_time = $_SERVER['REQUEST_TIME'];
		$expiry_time = date('Y-m-d H:i:s', $curr_time - self::$sess_max_life);
		$sth = $GLOBALS['dbh']->prepare('SELECT id, data FROM sessions WHERE session_id = :sess_id AND updated_at >= :exp_time');
		$sth->bindParam(':sess_id', $sess_id);
		$sth->bindParam(':exp_time', $expiry_time);
		$curr_date_time = date('Y-m-d H:i:s', $curr_time);
		if ($sth->execute()) {
			$result = $sth->fetch(PDO::FETCH_ASSOC);
			if (empty($result)) {
				return '';
			}
			$sth = $GLOBALS['dbh']->prepare('UPDATE sessions SET updated_at = :curr_time WHERE id = :id');
			$sth->bindParam(':curr_time', $curr_date_time);
			$sth->bindParam(':id', $result['id']);
			if ($sth->execute()) {
				return $result['data'];
			}
			echo "problem updating found record's updated_at after read session";
		}
		echo 'could not do lookup select sessions';
		return false;

/*
			setcookie(session_name(), '', $_SERVER['REQUEST_TIME']-10, '/');
			echo $sess_id = session_id();
			setcookie(session_name(), $sess_id);
			$sth = $GLOBALS['dbh']->prepare('INSERT INTO sessions (session_id, data, created_at, updated_at) VALUES (:session_id, "", :created_at, :updated_at)');
			$sth->bindParam(':session_id', $sess_id);
			$sth->bindParam(':created_at', $curr_date_time);
			$sth->bindParam(':updated_at', $curr_date_time);
			if ($sth->execute()) {
			
			}
			echo 'couldnt do insert for read session';
			return false;
*/
	}

	//it seems that with every write it does a read first, compiles the variables and adds the new ones to it and does a write.
	//also i think that session_start() causes a write...which means read first...unless a session_destroy is called
	//so im saing if its gona write to the session in any case, why not make the read do an insert, and the write do a update?
	//either way a session read is done and a (write, is done unless a destroy is called)
	//sessions are compiled, then written
	//first when session start is called, a dread is done...if no session destroy is called then a write is done before closing
	//session_destroy();	//if session destroy is called, it doesnt even bother writing!

	//all i need to do is update the existing record taht has been created at read
	function write($sess_id, $data)
	{
		if (!isset($GLOBALS['dbh'])) {$GLOBALS['dbh'] = Database_connections::get_connection();}
		$curr_time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
		$sth = $GLOBALS['dbh']->prepare('SELECT id, data FROM sessions WHERE session_id = :sess_id');
		$sth->bindParam(':sess_id', $sess_id);
		if ($sth->execute()) {
			$result = $sth->fetch(PDO::FETCH_ASSOC);
			if (!empty($result)) {
				$sth = $GLOBALS['dbh']->prepare('UPDATE sessions SET updated_at = :curr_time, data = :data WHERE id = :id');
				$sth->bindParam(':curr_time', $curr_time);
				$sth->bindParam(':data', $data);
				$sth->bindParam(':id', $result['id']);
			}
			else {
				//insert
				$sth = $GLOBALS['dbh']->prepare('INSERT INTO sessions (session_id, data, created_at, updated_at) VALUES (:session_id, :data, :created_at, :updated_at)');
				$sth->bindParam(':session_id', $sess_id);
				$sth->bindParam(':data', $data);
				$sth->bindParam(':created_at', $curr_time);
				$sth->bindParam(':updated_at', $curr_time);
			}
			if ($sth->execute()) {
				return true;
			}
			echo 'session write update or indert couldnt be done<br />';
		}
		echo 'session write look up could not be done.';
		return false;


/*
		//wtf happens of session id change????!!?
		if (!isset($GLOBALS['dbh'])) {$GLOBALS['dbh'] = Database_connections::get_connection();}
		$curr_time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
		$sth = $GLOBALS['dbh']->prepare('UPDATE sessions SET updated_at = :curr_time, data = :data WHERE session_id = :session_id');
		$sth->bindParam(':curr_time', $curr_time);
		$sth->bindParam(':data', $data);
		$sth->bindParam(':session_id', $sess_id);
		if ($sth->execute()) {
			return true;
		}
		echo 'session write look up could not be done.';
		return false;
*/


	}

	function destroy($sess_id)
	{
		$sth = $GLOBALS['dbh']->prepare('DELETE FROM sessions WHERE session_id = :sess_id');
		$sth->bindParam(':sess_id', $sess_id);
		
		//the way i see it, if u gona remove teh session, you might as well remove the cookie too!
		setcookie(session_name(), '', $_SERVER['REQUEST_TIME']-10, '/');

		return $sth->execute();
	}


	function gc($sess_max_life)
	{
		$expiry_time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME'] - $sess_max_life);
		$sth = $GLOBALS['dbh']->prepare('DELETE FROM sessions WHERE updated_at < :exp_time');
		$sth->bindParam(':exp_time', $expiry_time);		
		return $sth->execute();
	}


}


/*

   function sess_open($sess_path, $sess_name) {
      print "Session opened.<br />";
      print "Sess_path: $sess_path<br />";
      print "Sess_name: $sess_name<br /><br />";
      return true;
   }

   function sess_close() {
      print "Session closed.<br /><br />";
      return true;
   }

   function sess_read($sess_id) {
      print "Session read.<br />";
      print "Sess_ID: $sess_id<br /><br />";
      return '';
   }

   function sess_write($sess_id, $data) {
      print "Session value written.<br />";
      print "Sess_ID: $sess_id<br />";
      print "Data: $data<br /><br />";
      return true;
   }

   function sess_destroy($sess_id) {
		print "Session destroy called.<br />";
		print "Sess_ID: $sess_id<br /><br />";
      return true;
   }

   function sess_gc($sess_maxlifetime) {
      print "Session garbage collection called.<br />";
      print "Sess_maxlifetime: $sess_maxlifetime<br /><br />";
      return true;
   }
	print "session save handler being set now<br /><br />";
   session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
	print "session staring now<br /><br />";
    session_start();
//sessions are compiled, then written
//first when session start is called, a dread is done...if no session destroy is called then a write is done before closing
session_destroy();	//if session destroy is called, it doesnt even bother writing!
	print "session foo being set now<br /><br />";
    $_SESSION['foo'] = "bar";
   print "Some text<br /><br />";
	print "session baz being set now<br /><br />";
    $_SESSION['baz'] = "wombat";


	print "session foo being echoed now<br /><br />";
	echo $_SESSION['foo'],  "<br /><br />";

	print "session foo being unset now<br /><br />";
	unset($_SESSION['foo']);

	print "session foo being set now<br /><br />";
    $_SESSION['foo'] = "cat";

	print "session foo being echoed now<br /><br />";
	echo $_SESSION['foo'],  "<br /><br />";

*/

/*
error_reporting(E_ALL | E_STRICT);
require('/var/www/24/only_2_m/configuration/Database_connections.php');


//session_save_path ("database");
date_default_timezone_set('Jamaica');
session_name("gameCityJainfo");
ini_set("session.hash_function", 0);
ini_set("session.save_handler", 'user');
new Database_session_store();

// phpinfo();




session_start();
//echo session_id();

$_SESSION['apple'] = "pie";
$_SESSION['YAAY'] = "booo";
unset($_SESSION['YAAY']);
echo $_SESSION['apple'];
//setcookie(session_name(), '', time()-10, '/');
//session_destroy();

class Database_session_store {

	private static $sess_max_life = 0;

	function Database_session_store() {
		self::$sess_max_life = get_cfg_var("session.gc_maxlifetime");
		session_set_save_handler( 
			array(&$this, 'open'), 
			array(&$this, 'close'),
			array(&$this, 'read'),
			array(&$this, 'write'),
			array(&$this, 'destroy'),
			array(&$this, 'gc')
		);
	}

	function open($save_path, $session_name) {
		if (!isset($GLOBALS['dbh'])) {$GLOBALS['dbh'] = Database_connections::get_connection();}
		self::$sess_max_life = ini_get("session.gc_maxlifetime");

		return true;
	}

	function close() {
		//keeping a persistents db conn.
// 		$this->gc(self::$sess_max_life);
		return true;
	}

	function read($sess_id)
	{
		//updated_at = 1;$sess_max_life = 5;expiry = 6;	time() = 5.5;updated_at >= time() - $sess_max_life
// 		echo "read";
		$curr_time = $_SERVER['REQUEST_TIME'];
		$expiry_time = date('Y-m-d H:i:s', $curr_time - self::$sess_max_life);
		$sth = $GLOBALS['dbh']->prepare('SELECT id, data FROM sessions WHERE session_id = :sess_id AND updated_at >= :exp_time');
		$sth->bindParam(':sess_id', $sess_id);
		$sth->bindParam(':exp_time', $expiry_time);
		$sth->execute();
		$result = $sth->fetch(PDO::FETCH_ASSOC);
		if (!empty($result)) {
			$sth = $GLOBALS['dbh']->prepare('UPDATE sessions SET updated_at = :curr_time WHERE id = :id');
			$curr_date_time = date('Y-m-d H:i:s', $curr_time);
			$sth->bindParam(':curr_time', $curr_date_time);
			$sth->bindParam(':id', $result['id']);
			if ($sth->execute()) {
				return $result['data'];
			}
			echo "problem updating updated_at after read session";
			return false;
		}
		return '';
	}

	function write($sess_id, $data)
	{
		if (!isset($GLOBALS['dbh'])) {$GLOBALS['dbh'] = Database_connections::get_connection();}
// 		echo "write";
		$curr_time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
		$sth = $GLOBALS['dbh']->prepare('SELECT id, data FROM sessions WHERE session_id = :sess_id');
		$sth->bindParam(':sess_id', $sess_id);
		if ($sth->execute()) {
			$result = $sth->fetch(PDO::FETCH_ASSOC);
			if (!empty($result)) {
				$sth = $GLOBALS['dbh']->prepare('UPDATE sessions SET updated_at = :curr_time, data = :data WHERE id = :id');
				$sth->bindParam(':curr_time', $curr_time);
				$sth->bindParam(':data', $data);
				$sth->bindParam(':id', $result['id']);
			}
			else {
				//insert
				$sth = $GLOBALS['dbh']->prepare('INSERT INTO sessions (session_id, data, created_at, updated_at) VALUES (:session_id, :data, :created_at, :updated_at)');
				$sth->bindParam(':session_id', $sess_id);
				$sth->bindParam(':data', $data);
				$sth->bindParam(':created_at', $curr_time);
				$sth->bindParam(':updated_at', $curr_time);
			}
			return $sth->execute();
		}
		else {
			echo 'session write look up could not be done.';
			return false;
		}
	}

	function destroy($sess_id)
	{
		$sth = $GLOBALS['dbh']->prepare('DELETE FROM sessions WHERE session_id = :sess_id');
		$sth->bindParam(':sess_id', $sess_id);
		return $sth->execute();
	}


	function gc($sess_max_life)
	{
// 		echo "gc";
		$expiry_time = date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME'] - $sess_max_life);
		$sth = $GLOBALS['dbh']->prepare('DELETE FROM sessions WHERE updated_at <= :exp_time');
		$sth->bindParam(':exp_time', $expiry_time);
		return $sth->execute();
	}


}

*/



?>